import re
import os
import sys
import random
import faulthandler
faulthandler.enable()



class manager:
    clearCodePath = ''
    prefixArr = []
    garbageMethodPath = ''
    prefixArrPath = ''
    garbageMethodArr = []
    allMPath = []
    allHPath = []



    def start(self):
        print('目录下prefixArr.txt为以往用到过的所有垃圾前缀换行分割')
        print('目录下GarbageMethod.m为以往用到过的所有垃圾代码库，按原格式，原封不动复制过来，注意空格不要错，否则匹配不到')
        print('垃圾代码前缀与自己常规代码前缀一致的慎用！！！')
        print('老规矩，拖入需一键clear的路径')
        self.clearCodePath = input().strip()
        self.garbageMethodPath = os.path.dirname(__file__)+'/GarbageMethod.m'
        self.prefixArrPath = os.path.dirname(__file__)+'/prefixArr.txt'

        if os.path.exists(self.garbageMethodPath) and os.path.exists(self.prefixArrPath):
            methodNamefile = open(self.garbageMethodPath, 'r');
            self.garbageMethodArr = methodNamefile.readlines()
            if (len(self.garbageMethodArr) == 0):
                print("error:路径下GarbageMethod.m异常")
                return

            prefixNamefile = open(self.prefixArrPath, 'r');
            self.prefixArr = prefixNamefile.readlines()
            if (len(self.prefixArr) == 0):
                print("error:prefixArr.txt异常")
                return

        for root, dirs, files in os.walk(self.clearCodePath):
            for file in files:
                path = os.path.join(root, file)
                bool = path.endswith((".m"))
                if bool == True:
                    self.allMPath.append(path)


        index = 1
        allIndex = len(self.allMPath)

        for mPath in self.allMPath:
            self.clearMCode(mPath)
            self.clearHCode(mPath)
            print('清理进度%f'%(index / allIndex))
            if (index == allIndex):
                print('清理进度完成')
            index = index + 1



    def clearHCode(self,mPath):
        hPath=str(mPath).replace('.m','.h')
        isHavePath = os.path.exists(hPath)
        if isHavePath == False:
            print('不存在:'+hPath)
            return
        os.chmod(hPath, 0o777)
        codefile = open(hPath, 'r');
        codeText = codefile.read()
        ljPArr = []
        ljFuncNameArr = []
        for prefix in self.prefixArr:
            PPattern = r'@property'+ r'.*?' + prefix.strip() + r'.*?;\n'
            PResult = re.findall(PPattern, codeText)
            ljPArr.extend(PResult)
            funcPattern = r'-\ *\(void\)\ *' + prefix.strip() + r'.*?\;\n'
            funcResulf = re.findall(funcPattern, codeText)
            ljFuncNameArr.extend(funcResulf)
            funcAddPattern = r'\+\ *\(void\)\ *' + prefix.strip() + r'.*?\;\n'
            funcAddResulf = re.findall(funcAddPattern, codeText)
            ljFuncNameArr.extend(funcAddResulf)
        for Pcode in ljPArr:
            codeText = codeText.replace(Pcode, '')
        for FuncCode in ljFuncNameArr:
            codeText = codeText.replace(FuncCode, '')
        newFile = open(hPath, 'w')
        newFile.write(codeText)
        newFile.close()




    def clearMFunc(self,mPath,funcNameArr):
        locals()
        os.chmod(mPath, 0o777)
        codefile = open(mPath, 'r');
        codeTextArr = codefile.readlines()
        ljCodeArr = []
        for funcName in funcNameArr:
            ljoneCodeStrArr = []
            ljcodeStr = ""
            kuoHao = -2
            for codeText in codeTextArr:
                locals()
                if funcName in codeText and '//' not in codeText.strip()[0:2] :
                    kuoHao = 0
                    if '{' in codeText and '//' not in codeText.strip()[0:2]:
                        kuoHao = kuoHao + codeText.count('{')
                    if '}' in codeText and '//' not in codeText.strip()[0:2]:
                        kuoHao = kuoHao - codeText.count('}')
                    ljoneCodeStrArr.append(codeText)
                    if '{' not in codeText and '//' not in codeText.strip()[0:2]:
                        kuoHao = -1
                    if kuoHao == 0:
                        ljcodeStr = ''.join(ljoneCodeStrArr)
                        ljCodeArr.append(ljcodeStr)
                        break;
                    continue
                if  kuoHao == -2:
                    continue
                elif kuoHao > 0:
                    if '{' in codeText and '//' not in codeText.strip()[0:2]:
                        kuoHao = kuoHao + codeText.count('{')
                    if '}' in codeText and '//' not in codeText.strip()[0:2]:
                        kuoHao = kuoHao - codeText.count('}')
                    ljoneCodeStrArr.append(codeText)
                    if kuoHao == 0:
                        ljcodeStr = ''.join(ljoneCodeStrArr)
                        ljCodeArr.append(ljcodeStr)
                        break;
                    continue
                elif kuoHao == 0:
                    ljoneCodeStrArr.append(codeText)
                    ljcodeStr = ''.join(ljoneCodeStrArr)
                    ljCodeArr.append(ljcodeStr)
                    break;
                else:
                    if '{' in codeText and '//' not in codeText.strip()[0:2]:
                        kuoHao = 0
                    if '{' in codeText and '//' not in codeText.strip()[0:2]:
                        kuoHao = kuoHao + codeText.count('{')
                    if '}' in codeText and '//' not in codeText.strip()[0:2]:
                        kuoHao = kuoHao - codeText.count('}')
                    ljoneCodeStrArr.append(codeText)
                    if kuoHao == 0:
                        ljcodeStr = ''.join(ljoneCodeStrArr)
                        ljCodeArr.append(ljcodeStr)
                        break;
                    continue

        os.chmod(mPath, 0o777)
        codefile.close()
        codetextfile = open(mPath, 'r');
        codeText = codetextfile.read()
        for ljCode in ljCodeArr:
            codeText = codeText.replace(ljCode,'')
        newFile = open(mPath, 'w')
        newFile.write(codeText)
        newFile.close()















    def clearMCode(self,mPath):
        locals()
        os.chmod(mPath, 0o777)
        codefile = open(mPath, 'r');
        codeText = codefile.read()
        ljFunStrArr = self.getLjFuncArr()
        for ljCode in ljFunStrArr:
            codeText = codeText.replace(ljCode,'')

        ljTagArr = []
        ljFuncNameArr = []
        for prefix in self.prefixArr:
            tagPattern = r'//'+prefix.strip()+r'.*?\n'
            tagResult = re.findall(tagPattern, codeText)
            ljTagArr.extend(tagResult)
            funcPattern = r'\)\ *'+prefix.strip()+r'.*?\n'
            funcResulf = re.findall(funcPattern,codeText)
            ljFuncNameArr.extend(funcResulf)
            func2Pattern = r'\)\ *'+prefix.strip()+r'.*?:\('
            func2Resulf = re.findall(func2Pattern,codeText)
            ljFuncNameArr.extend(func2Resulf)
        for ljTagCode in ljTagArr:
            codeText = codeText.replace(ljTagCode,'')

        newFile = open(mPath, 'w')
        newFile.write(codeText)
        newFile.close()
        if len(ljFuncNameArr) >0:
            self.clearMFunc(mPath, ljFuncNameArr)



    def getLjFuncArr(self):
        ljFuncArr = []
        codeArr = []
        isStartAdd = False
        dicArr = []
        khCount = - 1
        ljCodeStr = ''
        for codeStr in self.garbageMethodArr:
            locals()
            if isStartAdd == True:
                codeArr.append(codeStr)
            if '{' in codeStr:
                if khCount == -1:
                    khCount = 0
                    isStartAdd = True
                khCount = khCount + codeStr.count('{')
            if '}' in codeStr:
                khCount = khCount - codeStr.count('}')
                if khCount == 0:
                    isStartAdd = False
                    khCount = -1
                    codeArr.pop()
                    ljCodeStr = ''.join(codeArr)
                    ljFuncArr.append(ljCodeStr)
                    ljCodeStr=''
                    codeArr = []
        return ljFuncArr
tool = manager()
tool.start()
